package com.cy.config;

import com.cy.common.Constant;
import com.cy.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.Filter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * @Author: cy
 * @Date: 2022/02/10/21:20
 * @Description:
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 静态资源不进行拦截
        web.ignoring().antMatchers("/resources/**");
    }


    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(
                        "/user/setting",
                        "/user/upload",
                        "/discuss-post/add",
                        "/comment/add/**",
                        "/message/letter/**",
                        "/message/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow"
                )
                .hasAnyAuthority(
                        Constant.AUTHORITY_USER,
                        Constant.AUTHORITY_ADMIN,
                        Constant.AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss-post/top",
                        "/discuss-post/wonderful"
                )
                .hasAnyAuthority(
                        Constant.AUTHORITY_MODERATOR        // 版主有置顶和加精权限
                )
                .antMatchers(
                        "/discuss-post/delete",
                        "/data/**"
                )
                .hasAnyAuthority(
                        Constant.AUTHORITY_ADMIN        // 管理员有删除权限和查看uv、DAU
                )
                .anyRequest().permitAll()   // 其他任何请求都被放行
                .and().csrf().disable();    // 关闭csrf

        http.exceptionHandling()
                // 没有登录时的处理
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
                            throws IOException, ServletException {
                        // 如果登录是普通的请求直接跳转到登录页面
                        // 如果登录是异步请求返回xml格式数据到前端，再由前端进行跳转打登录页面
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJsonString(403, "您还未登录,请重新登录！"));
                        } else {
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                // 权限不足时的处理
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {

                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJsonString(403, "您没有权限访问此页面！"));
                        } else {
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }

                    }
                });

        // security底层默认会拦截/logout请求，进行退出处理
        // 覆盖它默认的逻辑,才能执行我们自己的退出代码
        http.logout().logoutUrl("/securitylogout");



    }
}
